package me.ratel.demo.eBook.interfaces.utils;

import com.alibaba.fastjson.JSON;
import me.ratel.demo.eBook.infrastructure.utils.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Administrator
 * @time 2016/6/30 16:13
 */
public class ResponseUtil {
    private static final Logger logger = LoggerFactory.getLogger(ResponseUtil.class);

    /**
     * Writes a JSON response
     */
    public static void writeJSON(final HttpServletResponse response, Object object) {
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(JSON.toJSONString(object));
        } catch (IOException ioe) {
            logger.error("IOException in populateWithJSON", ioe);
        }
    }

    /**
     * Writes a XML response
     */
    public static void writeXML(final HttpServletResponse response, Object object) {
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/xml;charset=UTF-8");
        try {
            response.getWriter().write(XmlUtils.toXML(object));
        } catch (IOException ioe) {
            logger.error("IOException in populateWithJSON", ioe);
        }
    }
}
